/**
 * 
 */
package com.stylefeng.guns.core.intercept;
 
import java.net.URLEncoder;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.stylefeng.guns.core.filter.WxAuthFilter;
import com.stylefeng.guns.modular.shop.service.ITMemberService;
import com.stylefeng.guns.persistence.shop.model.TMember;
import com.stylefeng.web.utils.SessionUtil;
import com.stylefeng.web.wx.Constant;
import com.stylefeng.web.wx.WxConfigProperties;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
/**
 * @author chenlf
 * 
 *         2014-3-25
 */
public class MemberInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(MemberInterceptor.class);
    public final static String SEESION_MEMBER = "seesion_member";
    SessionUtil sessionUtil = new SessionUtil();
    @Autowired
    WxMpService wxMpService;

    @Autowired
    ITMemberService itMemberService;

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
                                Exception arg3) throws Exception {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
     */
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
                           ModelAndView arg3) throws Exception {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * 拦截mvc.xml配置的/member/**路径的请求
     * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        MDC.put("logId", RandomStringUtils.randomNumeric(8));

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String uri = httpServletRequest.getRequestURI();
        logger.info("request url={}?{}", uri, httpServletRequest.getQueryString());

        String wxOauth2Code = request.getParameter("code");
        String state = request.getParameter("state");
        TMember user = sessionUtil.getCurrentUser();
        logger.info("currentUser:{}", user);

        if (uri.startsWith(Constant.WX_H5_URI) && null == user
                && (org.apache.commons.lang3.StringUtils.isEmpty(state) || !sessionUtil.isExistState(state))) {
            logger.info("current user is null");

            String param = httpServletRequest.getQueryString();
            String redirectUrl = WxConfigProperties.pageDomain + uri;
            if (org.apache.commons.lang3.StringUtils.isNotBlank(param)) {
                redirectUrl += "?" + param;
            }
            String scope = "snsapi_userinfo";
            String wxOauth2Url = wxMpService.oauth2buildAuthorizationUrl(redirectUrl, scope, sessionUtil.getNewWxState());

            logger.info("wxOauth2Url={} scope={} state={} redirectUrl={}", wxOauth2Url, scope, state, redirectUrl);
            httpServletResponse.sendRedirect(wxOauth2Url);
            //跳转到 微信登录页面
            return true;
        }

        if (uri.startsWith(Constant.WX_H5_URI) && null == user
                && (org.apache.commons.lang3.StringUtils.isNotEmpty(wxOauth2Code) && org.apache.commons.lang3.StringUtils.isNotEmpty(state))
                && sessionUtil.isExistState(state)) {

            //处理用户
            try {
                user = itMemberService.getByWxOauthCode(wxOauth2Code);
                user.setToken(sessionUtil.generateToken());
                sessionUtil.setCurrentUser(httpServletResponse, user);
                Long uid = user.getId();
                if (null == uid) {
                    logger.info("----go to signup page------");
                    String toUrl = WxConfigProperties.pageDomain + Constant.VIEW_SIGNUP + "?token=" + user.getToken();
                    httpServletResponse.sendRedirect(toUrl);
                    return false;
                } else {
                    itMemberService.insert(user);
                    String toUrl = WxConfigProperties.pageDomain + "/wap";
                    httpServletResponse.sendRedirect(toUrl);
                    return true;
                }
            } catch (WxErrorException e) {
                logger.error("doFilter error.", e);
            }
            return true;
        }

        return true;
    }

 
}